package top.yzlin.jqueryjx3strategystation.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.yzlin.jqueryjx3strategystation.dao.ImageDAO;
import top.yzlin.jqueryjx3strategystation.entity.ImageDO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@ResponseBody
public class ImgController {
    private ImageDAO imageDAO;

    @Autowired
    public void setImageDAO(ImageDAO imageDAO) {
        this.imageDAO = imageDAO;
    }

    @PostMapping("/v2/api/updateImg")
    public JSONObject imgUpload(@RequestParam("upload") MultipartFile file) throws IOException {
        ImageDO imageDO=new ImageDO();
        imageDO.setData(file.getBytes());
        ImageDO save = imageDAO.save(imageDO);
        return new JSONObject().fluentPut("uploaded", 1).fluentPut("url", "/img/h2/" + save.getImageId());
    }


    @GetMapping(value = "/img/h2/{imgId}")
    public void getMessageImage(@PathVariable("imgId") Integer imgId, HttpServletResponse response) throws IOException {
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        if (imageDAO.findById(imgId).isPresent()) {
            response.getOutputStream().write(imageDAO.findById(imgId).map(ImageDO::getData).get());
        }
        response.setStatus(404);
    }
}
